<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\store\controller;

use app\admin\model\GoodsModel;
use app\admin\service\AddressService;
use app\store\model\StoreModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Request;

class AdminStoreController extends AdminBaseController
{
    function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $param=$this->request->param();
        $user_id=session('ADMIN_ID');

        if(isset($param['id'])){
            $id=$param['id'];
            $store=new StoreModel();
            $store_info=$store->get_store_info($id);
            if($user_id!=$store_info['user_id']&&$user_id!=1){
                $this->error('本店铺不属于您，请选择自己的店铺','/store/admin_store/index.html');
            }
            $action=request()->action();
            $this->assign('store_info',$store_info);
            $this->assign('action',$action);
        }
      
        $uid=cmf_get_current_admin_id();
        $flag=false;
      	if($uid==1){
        	$flag=true;
        }else{
          $where['user_id']=$uid;
          $where['role_id']=1;
          $rs=Db::name('role_user')->where($where)->find();
          if($rs){
          	$flag=true;
          }
        }
      if($flag){
        $store_list=Db::name('store')->field('id')->select()->toArray();
         $ids='';  
         foreach ($store_list as $k=>$v){
                if($k==0){
                    $ids=$v['id'];
                }else{
                    $ids=$ids.','.$v['id'];
                }
          }
        $tj_ids=$ids;
      }else{
        $tj_store_list=Db::name('store')->field('id')->where('rec_user_id',$uid)->select()->toArray();
        $store_list=Db::name('store')->field('id')->where('user_id',$uid)->select()->toArray(); 
        $ids='';       
        $tj_ids='';
        if($store_list){
            foreach ($store_list as $k=>$v){
                if($k==0){
                    $ids=$v['id'];
                }else{
                    $ids=$ids.','.$v['id'];
                }
            }
        }
        if($tj_store_list){
            foreach ($tj_store_list as $k=>$v){
                if($k==0){
                    $tj_ids=$v['id'];
                }else{
                    $tj_ids=$tj_ids.','.$v['id'];
                }
            }
       
        }
      
      }        
   
        $this->ids=$ids;        
        $this->tj_ids=$tj_ids;

    }

    /**
     * 店铺列表
     * @adminMenu(
     *     'name'   => '店铺列表',
     *     'parent' => 'store/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '店铺列表',
     *     'param'  => ''
     * )
     */
    function index(){
        $param = $this->request->param();
        $store=new StoreModel();
        $user_id=session('ADMIN_ID');
		if($user_id==1){
        	$user_id=0;
        }else{
          $data['role_id']=1;
          $data['user_id']=$user_id;
          $rs=Db::name('RoleUser')->where($data)->find();
          	if($rs){
            	$user_id=0;
            }
        }
        $data = $store->store_list($param,true,$user_id);
        $data->appends($param);
        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('store_list', $data->items());
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /**
     * 店铺审核
     * @adminMenu(
     *     'name'   => '店铺审核',
     *     'parent' => 'store/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '店铺审核',
     *     'param'  => ''
     * )
     */
    function index_shenhe(){
        $param = $this->request->param();
        $store=new StoreModel();
        $user_id=session('ADMIN_ID');
        if($user_id==1){
            $user_id=0;
        }else{
            $data['role_id']=1;
            $data['user_id']=$user_id;
            $rs=Db::name('RoleUser')->where($data)->find();
            if($rs){
                $user_id=0;
            }
        }
        $data = $store->store_list($param,true,$user_id);
        $data->appends($param);
        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('store_list', $data->items());
        $this->assign('page', $data->render());
        return $this->fetch();
    }
    /**
     * 店铺审核操作
     * @adminMenu(
     *     'name'   => '店铺审核操作',
     *     'parent' => 'index_shenhe',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '店铺审核操作',
     *     'param'  => ''
     * )
     */
    function index_status(){
        $param=$this->request->param();
        $data['status']=$param['status'];
        $store=new StoreModel();
        $rs=$store->where('id',$param['store_id'])->update($data);
        if($rs){
            $this->success('操作成功');
        }else{
            $this->success('操作失败');
        }
    }
    /**
     * 添加店铺
     * @adminMenu(
     *     'name'   => '添加店铺',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加店铺',
     *     'param'  => ''
     * )
     */
    function add(){
        //获取省
        if(request()->isPost()){
            $param=$this->request->param();
            $store=new StoreModel();
            $post=$param['post'];
            $res=$this->validate($post,'store');
            if($res!== true){
                $this->error($res);
            }
            if (!empty($param['photo_names']) && !empty($param['photo_urls'])) {
                $post['more']['photos'] = [];
                foreach ($param['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push( $post['more']['photos'], ["url" => $photoUrl, "name" => $param['photo_names'][$key]]);
                }
            }
          $post['rec_user_id']=isset($post['rec_user_id'])?$post['rec_user_id']:0;
            if($post['user_id']==$post['rec_user_id']){
                $this->error('推荐人和绑定用户不能相同');
            }
            $addStore=$store->add_store($post);
            $this->success('添加成功!', url('admin_store/edit', ['id' => $addStore->id]));
        }else{
            $dataAddress = new AddressService();
            $Address_list = $dataAddress->getProvinceList();
            $this->assign('Address_list', $Address_list);
            return $this->fetch();
        }

    }

    /**
     * 编辑店铺
     * @adminMenu(
     *     'name'   => '编辑店铺',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑店铺',
     *     'param'  => ''
     * )
     */
    function edit(){
        $param=$this->request->param();
        if(request()->isPost()){
            $param=$this->request->param();
            $store=new StoreModel();
            $post=$param['post'];
            $res=$this->validate($post,'store');
            if($res!== true){
                $this->error($res);
            }
            if (!empty($param['photo_names']) && !empty($param['photo_urls'])) {
                $post['more']['photos'] = [];
                foreach ($param['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push( $post['more']['photos'], ["url" => $photoUrl, "name" => $param['photo_names'][$key]]);
                }
            }
           $post['rec_user_id']=isset($post['rec_user_id'])?$post['rec_user_id']:0;
            if($post['user_id']==$post['rec_user_id']){
                $this->error('推荐人和绑定用户不能相同');
            }
            $addStore=$store->add_store($post);
            $this->success('保存成功!');
        }else{
            $dataAddress=new AddressService();
            $Address_list=$dataAddress->getProvinceList();
            $id=$param['id'];
            $store=new StoreModel();
            $store_info=$store->get_store_info($id);
            $city_list=$dataAddress->getCityList($store_info['province_id']);
            $District_list=$dataAddress->getDistrictList($store_info['city_id']);
            $this->assign('city_list',$city_list);
            $this->assign('District_list',$District_list);
            $this->assign('Address_list',$Address_list);
            $this->assign('store_info',$store_info);
            return $this->fetch();
        }
    }
    /**
     * 删除店铺
     * @adminMenu(
     *     'name'   => '删除店铺',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除店铺',
     *     'param'  => ''
     * )
     */
    function delete(){
        $Store = new StoreModel();
        $data            = $this->request->param();
        $result = $Store->adminDeleteStore($data);
        if ($result) {
            $this->success(lang('DELETE_SUCCESS'));
        } else {
            $this->error(lang('DELETE_FAILED'));
        }

    }

    /**
     * 店铺首页
     * @adminMenu(
     *     'name'   => '店铺首页',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '店铺首页',
     *     'param'  => ''
     * )
     */
    function info(){
        $param=$this->request->param();
        $id=$param['id'];
        $store=new StoreModel();
        $store_info=$store->get_store_info($id);
        $area= get_city_info($store_info['province_id'],$store_info['city_id'],$store_info['district_id']);

        $where['shop_id']=$id;
        $tj_order_count=Db::name('order')->where($where)->count();

        $map['store_id']=$id;
        $map['pay_status']=1;
        $tj_cards_count=Db::name('order_card')->where($map)->count();
        $type=1;
        $tj_store=$store->get_tj_list($id,$type);

        $this->assign('tj_store',$tj_store);
        $this->assign('tj_order_count',$tj_order_count);
        $this->assign('tj_cards_count',$tj_cards_count);
        $this->assign('area',$area);
        $this->assign('store_info',$store_info);
        $this->assign('store_id',$id);
        return $this->fetch();
    }
    /**
     * 推荐店铺
     * @adminMenu(
     *     'name'   => '推荐店铺',
     *     'parent' => 'store/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '推荐店铺',
     *     'param'  => ''
     * )
     */
    function stock(){
        $ids=$this->tj_ids;
        $store=new StoreModel();
        $data=$store->get_tj_list($ids,2);
        $this->assign('tj_list', $data->items());
        $this->assign('pages', $data->render());
        return $this->fetch();
    }

    /**
     * 管理店铺配卡
     * @adminMenu(
     *     'name'   => '管理店铺配卡',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理店铺配卡',
     *     'param'  => ''
     * )
     */
    function card(){
        $param=$this->request->param();
        if(request()->isPost()) {
            $param['seven_days_card']=isset($param['seven_days_card'])?1:0;
            $param['monthly_card']=isset($param['monthly_card'])?1:0;
            $param['half_year_card']=isset($param['half_year_card'])?1:0;
            $param['year_card']=isset($param['year_card'])?1:0;
            $store=new StoreModel();
            $store->edit_card($param);
            $this->success('保存成功!');
        }else{
            $id = $param['id'];
            $store=new StoreModel();
            $store_info=$store->get_store_info($id);
            $card_info=$store->get_card($id);

            $this->assign('card_info', $card_info);
            $this->assign('store_info', $store_info);
            $this->assign('store_id', $id);
            return $this->fetch();
        }
    }

    /**
     * 会员卡订单
     * @adminMenu(
     *     'name'   => '会员卡订单',
     *     'parent' => 'store/AdminIndex/default',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '会员卡订单',
     *     'param'  => ''
     * )
     */
    function user_card(){
        $ids=$this->ids;
        $param=request()->param();
        $where['a.store_id']=['in',$ids];
        $where['a.pay_status']=1;
        $param['is_jiesuan']=isset($param['is_jiesuan'])?$param['is_jiesuan']:0;
        $param['order_no']=isset($param['order_no'])?$param['order_no']:'';
        $param['mobile']=isset($param['mobile'])?$param['mobile']:'';
        if($param['is_jiesuan']>0){
            if($param['is_jiesuan']==2){
                $where['a.is_jiesuan']=0;
            }
            if($param['is_jiesuan']==1){
                $where['a.is_jiesuan']=['neq',0];
            }
        }
        if($param['order_no']){
            $where['a.order_no']=['like','%'.$param['order_no'].'%'];
        }
        if($param['mobile']){
            $where['user.mobile']=$param['mobile'];
        }
        $this->assign('is_jiesuan',$param['is_jiesuan']);
        $this->assign('order_no',$param['order_no']);
        $this->assign('mobile',$param['mobile']);

        $tj_cards=Db::name('order_card')
            ->alias('a')
            ->join('user','user.id=a.uid')
            ->field('user.mobile,a.*')
            ->where($where)->order('a.id desc')->paginate(10);
        $tj_cards->appends($param);
        $this->assign('tj_cards', $tj_cards->items());
        $this->assign('pages',  $tj_cards->render());
        return $this->fetch();
    }

    /**
     * 管理推荐订单
     * @adminMenu(
     *     'name'   => '推荐订单',
     *     'parent' => 'store/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理推荐订单',
     *     'param'  => ''
     * )
     */
    function tj_order(){
        $param=$this->request->param();
        $param['is_jiesuan']=isset($param['is_jiesuan'])?$param['is_jiesuan']:0;
        $param['order_no']=isset($param['order_no'])?$param['order_no']:'';
        $param['store_id']=isset($param['store_id'])?$param['store_id']:0;
        if($param['is_jiesuan']>0){
            if($param['is_jiesuan']==1){
                $where['order_status']=13;
            }
            if($param['is_jiesuan']==2){
                $where['order_status']=['neq',13];
            }
        }
        if($param['order_no']){
            $where['order_no']=['like','%'.$param['order_no'].'%'];
        }

        //获取店铺列表
        $store=new StoreModel();
        $user_id=session('ADMIN_ID');
        if($user_id==1){
            $user_id=0;
        }else{
            $data['role_id']=1;
            $data['user_id']=$user_id;
            $rs=Db::name('RoleUser')->where($data)->find();
            if($rs){
                $user_id=0;
            }
        }
        $store_list = $store->adminStoreList($param,false,true,$user_id);
        $this->assign('store_list',$store_list);
        $ids=$this->ids;
        if($param['store_id']>0){
            $where['shop_id']=$param['store_id'];
        }else{
            $where['shop_id']=['in',$ids];
        }
        $tj_order=Db::name('order')
                ->where($where)
                ->order('order_id desc')
                ->paginate(10);
        $tj_order->appends($param);
        $this->assign('is_jiesuan',$param['is_jiesuan']);
        $this->assign('order_no',$param['order_no']);
        $this->assign('store_id',$param['store_id']);
        $this->assign('tj_order', $tj_order->items());
        $this->assign('pages',  $tj_order->render());
        return $this->fetch();

    }
    /**
     * 管理子店铺推荐订单
     * @adminMenu(
     *     'name'   => '子店铺订单',
     *     'parent' => 'store/AdminIndex/default',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理子店铺推荐订单',
     *     'param'  => ''
     * )
     */
    function tj_son_order(){
        $param=$this->request->param();
        $param['is_jiesuan']=isset($param['is_jiesuan'])?$param['is_jiesuan']:0;
        $param['order_no']=isset($param['order_no'])?$param['order_no']:'';
        $param['store_id']=isset($param['store_id'])?$param['store_id']:0;
    
        if($param['is_jiesuan']>0){
            if($param['is_jiesuan']==1){
                $where['order_status']=13;
            }
            if($param['is_jiesuan']==2){
                $where['order_status']=['neq',13];
            }
        }
        if($param['order_no']){
            $where['order_no']=['like','%'.$param['order_no'].'%'];
        }


        $ids=$this->tj_ids;

        $store=new StoreModel();
        $store_list=$store->get_tj_list($ids,3);
        $this->assign('store_list',$store_list);

        if($param['store_id']>0){
            $where['shop_id']=$param['store_id'];
        }else{
            $where['shop_id']=['in',$ids];
        }
        $tj_son_order= Db::name('order')->where($where)
                ->order('order_id desc')
                ->paginate(10);

        $where2['shop_id']=['in',$ids];
        $tj_son_order->appends($param);
        $this->assign('is_jiesuan',$param['is_jiesuan']);
        $this->assign('order_no',$param['order_no']);
        $this->assign('store_id',$param['store_id']);
        $this->assign('tj_order', $tj_son_order->items());
        $this->assign('pages',  $tj_son_order->render());
        return $this->fetch();
    }
    /**
     * 会员卡结算
     * @adminMenu(
     *     'name'   => '会员卡结算',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理子店铺推荐订单',
     *     'param'  => ''
     * )
     */
    function card_jiesuan(){
        $param=$this->request->param();
        $flag=0;
        if(isset($param['id'])){
            Db::startTrans();
            try{
                $card_order_info=Db::name('order_card')->find($param['id']);
                if($card_order_info['is_jiesuan']==0){
                    //店铺信息
                    $store_info=Db::name('store')->find($card_order_info['store_id']);
                    //店铺绑定用户信息
                    $user_info= Db::name('user')->find($store_info['user_id']);
                    //购买用户信息
                    $buy_user_info= Db::name('user')->find($card_order_info['uid']);
                    $tjmoney=0;
                    if($buy_user_info['tj_user']>0){
                        //推荐人获利 6%
                        $tjmoney=$card_order_info['price']*0.06;
                        $tj_user_info= Db::name('user')->find($buy_user_info['tj_user']);
                        Db::name('user')->where('id',$buy_user_info['tj_user'])->setInc('balance', $tjmoney);

                        //添加记录
                        $balance_info['user_id']=$buy_user_info['tj_user'];
                        $balance_info['create_time']=time();
                        $balance_info['change']=$tjmoney;
                        $balance_info['balance']=$buy_user_info['balance']+$tjmoney;
                        $balance_info['description']='异业联盟推荐会员卡收入';
                        $balance_info['remark']=json_encode($card_order_info);
                        Db::name('user_balance_log')->insert($balance_info);
                    }
                    $money=$card_order_info['price']-$tjmoney;
                    Db::name('user')->where('id',$store_info['user_id'])->setInc('balance', $money);

                    //添加记录
                    $balance_info['user_id']=$store_info['user_id'];
                    $balance_info['create_time']=time();
                    $balance_info['change']=$money;
                    $balance_info['balance']=$user_info['balance']+$money;
                    $balance_info['description']='会员卡收入';
                    $balance_info['remark']=json_encode($card_order_info);
                    Db::name('user_balance_log')->insert($balance_info);

                    //更新订单
                    $order_info['is_jiesuan']=1;
                    Db::name('order_card')->where('id',$card_order_info['id'])->update($order_info);
                    Db::commit();
                    $flag=1;
                }else{
                    $flag=2;
                }
            } catch (\Exception $e) {
                // 回滚事务
                $flag=0;
                file_put_contents('log/error.txt',var_export($e,true),FILE_APPEND);
                Db::rollback();
            }
            if($flag==0){
                $this->error('结算失败');
            }
            if($flag==1){
                $this->success('结算成功');
            }
            if($flag==2){
                $this->success('该订单已结算');
            }
        }
    }

    function order_jiesuan(){
        $param=$this->request->param();
        $flag=0;
        $order_info=Db::name('order')->find($param['id']);
        if($order_info['order_status']==4||$order_info['order_status']==7||$order_info['order_status']==11||$order_info['order_status']==12){
            Db::startTrans();
            try{
                if($order_info['order_status']==4||$order_info['order_status']==7||$order_info['order_status']==11){
                    //结算金额
                    $money=$order_info['pay_money']*0.2;
                    $tjmoney=$order_info['pay_money']*0.05;
                }
                if($order_info['order_status']==12){
                    //结算金额
                    $money=($order_info['pay_money']-$order_info['refund_require_money'])*0.2;
                    $tjmoney=($order_info['pay_money']-$order_info['refund_require_money'])*0.05;
                }
                if($money>0){
                    $store_info=Db::name('store')->find($order_info['shop_id']);
                    $user_info= Db::name('user')->find($store_info['user_id']);
                    Db::name('user')->where('id',$store_info['user_id'])->setInc('balance', $money);

                    //添加记录
                    $balance_info['user_id']=$store_info['user_id'];
                    $balance_info['create_time']=time();
                    $balance_info['change']=$money;
                    $balance_info['balance']=$user_info['balance']+$money;
                    $balance_info['description']='订单：'.$order_info['order_no'].'收入20%';
                    $balance_info['remark']=json_encode($order_info);
                    Db::name('user_balance_log')->insert($balance_info);
                    if($store_info['rec_user_id']) {
                        $tj_user_info= Db::name('user')->find($store_info['rec_user_id']);
                        Db::name('user')->where('id',$store_info['rec_user_id'])->setInc('balance', $tjmoney);

                        //添加记录
                        $balance_info['user_id']=$store_info['rec_user_id'];
                        $balance_info['create_time']=time();
                        $balance_info['change']=$tjmoney;
                        $balance_info['balance']=$tj_user_info['balance']+$tjmoney;
                        $balance_info['description']='订单：'.$order_info['order_no'].'收入5%';
                        $balance_info['remark']=json_encode($order_info);
                        Db::name('user_balance_log')->insert($balance_info);
                    }
                }

                $data2['order_status']=13;
                Db::name('order')->where('order_id',$order_info['order_id'])->update($data2);
                Db::commit();
                $flag=1;

            } catch (\Exception $e) {
                // 回滚事务
                $flag=0;
                file_put_contents('log/error.txt',var_export($e,true),FILE_APPEND);
                Db::rollback();
            }
            if($flag==1){
                $this->success('结算成功');
            }
            if($flag==0){
                $this->error('结算失败');
            }
        }else{
            $this->error('该订单暂时无法结算');
        }

    }

}
